package com.LeeCode;

/**
 * 统计最大元素出现至少 K 次的子数组
 */

public class Code2962 {
    public static void main(String[] args) {
        int[] nums = {1, 4, 2, 1};
        int k = 1;
        System.out.println(new Code2962().countSubarrays(nums, k));
    }

    public long countSubarrays(int[] nums, int k) {
        long ans = 0;
        int maxNum = nums[0];
        for (int num : nums) {
            maxNum = Math.max(maxNum, num);
        }
        int left, right = 0, count = 0;
        for (left = 0; left < nums.length; left++) {
            while (count < k && right < nums.length) {
                if (nums[right] == maxNum) {
                    count++;
                }
                right++;
            }
            if (count == k) {
                ans += nums.length - right + 1;
            }
            if (nums[left] == maxNum) {
                count--;
            }
        }
        return ans;
    }
}
